<?php

namespace application\controller;

use application\BaseController;
use fastphp\util\CrudGenerator;
use fastphp\facade\Config; // 导入Config门面

/**
 * 代码生成器控制器
 */
class Generator extends BaseController
{
    /**
     * 代码生成器首页
     */
    public function index()
    {
        $generator = new CrudGenerator();
        $tables = $generator->getTables();

        $this->set('tables', $tables);
        $this->set('active', 'generator');
        $this->render('admin/generator/index');
    }

    /**
     * 获取表结构信息
     */
    public function getTableInfo()
    {
        // 使用request()方法获取Request实例
        $tableName = $this->request()->post('table_name');

        if (empty($tableName)) {
            $this->error('表名不能为空');
        }

        $generator = new CrudGenerator();
        $columns = $generator->getColumns($tableName);

        // 修正success方法参数顺序
        $this->success(['columns' => $columns], '获取成功');
    }

    /**
     * 生成代码
     */
    public function generate()
    {
        // 使用request()方法获取Request实例
        $tableName = $this->request()->post('table_name');
        $tableDisplayName = $this->request()->post('table_display_name');

        if (empty($tableName)) {
            $this->error('表名不能为空');
        }

        if (empty($tableDisplayName)) {
            // 如果没有提供显示名称，使用表名
            // 使用Config门面获取配置
            $prefix = Config::get('database.prefix', '');
            if ($prefix && strpos($tableName, $prefix) === 0) {
                $tableDisplayName = substr($tableName, strlen($prefix));
            } else {
                $tableDisplayName = $tableName;
            }
        }

        $generator = new CrudGenerator();
        $results = $generator->generate($tableName, $tableDisplayName);

        if (isset($results['error'])) {
            $this->error($results['error']);
        }

        // 生成路由信息
        $controllerName = $generator->toCamelCase($tableDisplayName, true);
        $lowerName = $generator->toCamelCase($tableDisplayName, false);

        // 修正路由语法
        $routeInfo = <<<EOF
// {$controllerName}控制器路由
Router::get('/admin/${lowerName}', '${controllerName}','index');
Router::get('/admin/${lowerName}/add', '${controllerName}','add');
Router::post('/admin/${lowerName}/save', '${controllerName}','save');
Router::get('/admin/${lowerName}/edit', '${controllerName}','edit');
Router::post('/admin/${lowerName}/update', '${controllerName}','update');
Router::get('/admin/${lowerName}/delete', '${controllerName}','delete');
EOF;

        // 修正success方法参数顺序和返回数据
        $this->success([
            'results' => $results,
            'route_info' => $routeInfo,
            'controller_name' => $controllerName,
            'route_name' => $lowerName
        ], '代码生成成功');
    }
}
